#include <qrencode.h>
#include <QDebug>
#include <QPainter>

#include "qrwidget.h"

namespace Widget
{

class QRWidgetPrivate
{
public:
    QRWidgetPrivate(QRWidget* q);

    QRWidget* q_ptr;
    QString text;

};

QRWidgetPrivate::QRWidgetPrivate(QRWidget *q) : q_ptr(q)
{

}

QRWidget::QRWidget(QWidget *parent) : QWidget(parent)
{
    d_ptr = new QRWidgetPrivate(this);
}

QRWidget::~QRWidget()
{
    delete d_ptr;
}

void QRWidget::setText(const QString& text)
{
    if (d_ptr->text != text) {
        d_ptr->text = text;
        update();
    }
}

QString QRWidget::text() const
{
    return d_ptr->text;
}

QSize QRWidget::sizeHint() const
{
    return QSize(200, 200);
}

void QRWidget::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    QRcode *qr = QRcode_encodeString(d_ptr->text.toStdString().c_str(), 1, QR_ECLEVEL_H, QR_MODE_8, 0);
    if(qr) {
        QColor fg("black");
        QColor bg("white");
        painter.setBrush(bg);
        painter.setPen(Qt::NoPen);
        painter.drawRect(0,0,width(),height());
        painter.setBrush(fg);
        const int s=qr->width>0?qr->width:1;
        const double w=width();
        const double h=height();
        const double aspect=w/h;
        const double scale=((aspect>1.0)?h:w)/s;
        for(int y=0;y<s;y++){
            const int yy=y*s;
            for(int x=0;x<s;x++){
                const int xx=yy+x;
                const unsigned char b=qr->data[xx];
                if(b &0x01){
                    const double rx1=x*scale, ry1=y*scale;
                    QRectF r(rx1, ry1, scale, scale);
                    painter.drawRects(&r,1);
                }
            }
        }
        QRcode_free(qr);
    } else {
        QColor error("red");
        painter.setBrush(error);
        painter.drawRect(0,0,width(),height());
        qDebug()<<"QR FAIL: "<< strerror(errno);
    }
    qr = nullptr;
}

} // namespace widget
